import { login, logout, resetPwd } from '@/api/user'
import { getCookie, setCookie, removeCookie } from '@/utils/index'

const user = {
  state: {
    token: getCookie('a_token'),
    name: getCookie('u_nike'),
    avatar: '',
    roles: []
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(response => {
            const data = response.data
            setCookie('a_token', data.a_token)
            setCookie('u_nike', data.u_nike)
            commit('SET_TOKEN', data.a_token)
            commit('SET_NAME', data.u_nike)
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 登录
    ResetPwd({ dispatch, commit }, params) {
      return new Promise((resolve, reject) => {
        resetPwd(params)
          .then(response => {
            console.log(response)
            return dispatch('LogOut').then(() => {
              console.log('LogOut')
              resolve()
            })
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout()
          .then(response => {
            commit('SET_TOKEN', '')
            removeCookie('a_token')
            removeCookie('u_nike')
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 登出
    // LogOut({ commit, state }) {
    //   return new Promise((resolve, reject) => {
    //     logout({ a: 'a' })
    //       .then(() => {
    //         commit('SET_TOKEN', '')
    //         removeToken()
    //         resolve()
    //       })
    //       .catch(error => {
    //         reject(error)
    //       })
    //   })
    // },

    // 前端 登出 清除本地token 不访问接口
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeCookie('a_token')
        resolve()
      })
    }
  }
}

export default user
